package com.xin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.xin.entity.*;
import com.xin.mapper.SOrgDao;
import com.xin.mapper.UTeacherInfoDao;
import com.xin.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xin.util.CategoryEnum;
import com.xin.util.CategoryUtil;
import com.xin.util.PinYinUtil;
import com.xin.util.TeacherLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 教师信息 服务实现类
 * </p>
 *
 * @author l1
 * @since 2017-10-23
 */
@Service
public class UTeacherInfoServiceImpl extends ServiceImpl<UTeacherInfoDao, UTeacherInfo> implements UTeacherInfoService {

    @Autowired
    private SOrgService sOrgService;

    @Autowired
    private STeacherResourcesService sTeacherResourcesService;

    @Autowired
    private UWorkExperienceService uWorkExperienceService;

    @Autowired
    private UDegreeChangesService uDegreeChangesService;

    @Autowired
    private UTitleChangesService uTitleChangesService;

    @Autowired
    private UPositionChangesService uPositionChangesService;

    //教学业绩
    @Autowired
    private UTeachingPerformanceService uTeachingPerformanceService;

    //教学评价
    @Autowired
    private UTeachingEvaluationService uTeachingEvaluationService;

    //科研成果
    @Autowired
    private UResearchResultsService uResearchResultsService;

    //学习进修
    @Autowired
    private UStudyAndTrainingService uStudyAndTrainingService;

    //社会兼职
    @Autowired
    private USocialPartTimeService uSocialPartTimeService;

    //荣誉获奖
    @Autowired
    private UHonorAwardService uHonorAwardService;

    @Override
    public List<JSONObject> statCategory(String subjectCategory) {
        return super.baseMapper.statCategory(subjectCategory);
    }

    @Override
    public List<JSONObject> statSubject(String subjectCategory, String subjectAttribution) {
        return super.baseMapper.statSubject(subjectCategory,subjectAttribution);
    }

    @Override
    public List<JSONObject> statprofessional(String subjectCategory, String subjectAttribution, String prefessionalAttribution) {
        return super.baseMapper.statprofessional(subjectCategory,subjectAttribution,prefessionalAttribution);
    }

    @Override
    public void statJobCategoryByStatus(JSONObject statCategorye) {
    }

    @Override
    public void splitOrgs(List<SOrg> orgs,List<String> ones,Map<String,List<String>> twoeMap){
        if(orgs==null || orgs.isEmpty()) return;
        orgs.forEach(sOrg -> {
            Integer level = sOrg.getLevel();
            String sOrgName = sOrg.getName();

            //
            if(level == TeacherLevel.ONE.getLevel()){
                ones.add(sOrgName);
            }else  if(level == TeacherLevel.TWO.getLevel()){
                SOrg parentOrg = sOrgService.selectById(sOrg.getParentId());
                String parentOrgName = parentOrg.getName();
                List<String> twoList = twoeMap.getOrDefault(parentOrgName, new ArrayList<>());
                twoList.add(sOrgName);
                twoeMap.put(parentOrgName,twoList);
            }
//            else  if(level == TeacherLevel.THREE.getLevel()){
//                SOrg parentOrg = sOrgService.selectById(sOrg.getParentId());
//                String parentOrgName = parentOrg.getName();
//                List<String> threeList = threeMap.getOrDefault(parentOrgName, new ArrayList<>());
//                threeList.add(sOrgName);
//                threeMap.put(parentOrgName,threeList);
//            }

        });
    }
    @Override
    public List<JSONObject> statHomeByOrgs(UTeacherInfo utInfo, List<SOrg> orgs,JSONObject params) {
        List<JSONObject> result = new ArrayList<>();
        List<String> ones = new ArrayList<>();
        Map<String,List<String>> twoeMap= new HashMap<>();

        splitOrgs(orgs,ones,twoeMap);

        if(ones.isEmpty() && twoeMap.isEmpty()) return  null;
        // 一级目录
        if(!ones.isEmpty()){
            List<JSONObject> oneResult = statCategoryData(ones,params);
            if(! oneResult.isEmpty()){
                result.addAll(oneResult);
            }
        }
        // 二级结构
        if(!twoeMap.isEmpty()){
            List<JSONObject> twoResult = statSubjectData(twoeMap,params);
            if(!twoResult.isEmpty()){
                result.addAll(twoResult);
            }
        }
        // 三级结构

        return result;
    }


//    /**
//     * 统计三级目录
//     * @param
//     * @return
//     */
//    private List<JSONObject> statProfessionalData(Map<String,List<String>> threeMap,JSONObject params) {
//        // 根据 一级目录 和 二级目录统计
//        List<JSONObject> categoryList = new ArrayList<>();
//        if(threeMap.isEmpty()) return categoryList;
//        threeMap.forEach((key,value)->{
//            List<JSONObject> jsonObjects = baseMapper.statSubjectByProfessional(key, value);
//            //分类
//            jsonObjects.forEach(statCategorye->{
//                String subjectAttribution = statCategorye.getString("subjectAttribution");
//
//                // 一级目录:　在职 退休 按照岗位统计
//                List<JSONObject> statuses = baseMapper.statStatusByProfession(subjectAttribution, value);
//                statuses.forEach(status->{
//                    String statusName = status.getString("status");
//                    String statusNamePin = PinYinUtil.convertPY(statusName);
//
//                    // 一级目录 统计岗位
//                    List<JSONObject> jobCategoryes = baseMapper.statJobCategory(null, subjectAttribution,null, statusName);
//                    jobCategoryes.forEach(jsonObject -> {
//                        String jobCategory = jsonObject.getString("jobCategory");
//                        String toPinyinString = PinYinUtil.convertPY(jobCategory);
//                        Integer jobCategoryNums = jsonObject.getInteger("jobCategoryNums");
//                        status.put(toPinyinString,jobCategoryNums);
//
//                    });
//                    statCategorye.put(statusNamePin,status);
//                });
//
//
//                List<JSONObject> subjectes  = new ArrayList<>();
//                value.forEach(professionalAttribution->{
//                    JSONObject subject = new JSONObject();
//                    // 二级目录: 在职 退休
//                    List<JSONObject> statusJSONes = baseMapper.statStatus(null, subjectAttribution,professionalAttribution);
//                    statusJSONes.forEach(status-> {
//                        String statusName = status.getString("status");
//                        String statusNamePin = PinYinUtil.convertPY(statusName);
//                        Integer statusNums = status.getInteger("statusNums");
//                        subject.put(statusNamePin,statusNums);
//                    });
//
//                    // 二级目录: 管理,教师,工勤,专业技术,其他 按照 岗位级别统计
//                    List<JSONObject> jobCategoryes = baseMapper.statJobCategory(null, subjectAttribution,professionalAttribution, null);
//                    jobCategoryes.forEach(jobCategory->{
//                        String jobCategoryName = jobCategory.getString("jobCategory");
//                        String jobCategoryNamePinYin = PinYinUtil.convertPY(jobCategoryName);
//                        Integer jobCategoryNums = jobCategory.getInteger("jobCategoryNums");
//                        //按岗位级别查询
//                        List<JSONObject> jobLeveles = baseMapper.statJobLevel(null, subjectAttribution,professionalAttribution, jobCategoryName);
//                        jobLeveles.forEach(jobLevel->{
//                            String jobLevelName = jobLevel.getString("jobLevel");
//                            Integer jobLevelNums = jobLevel.getInteger("jobLevelNums");
//                            jobCategory.put(jobLevelName,jobLevelNums);
//                        });
//                        // 岗位统计
//                        subject.put(jobCategoryNamePinYin,jobCategory);
//
//                    });
//
//                    subjectes.add(subject);
//                });
//
//
//                statCategorye.put("subjectes",subjectes);
//
//                categoryList.add(statCategorye);
//            });
//        });
//
//        return categoryList;
//    }

    private List<JSONObject> statSubjectData(Map<String,List<String>> twoMap,JSONObject params) {
        // 根据 一级目录 和 二级目录统计
        List<JSONObject> categoryList = new ArrayList<>();
        if(twoMap.isEmpty()) return  categoryList;
        twoMap.keySet().forEach(key->{
            List<String> value = twoMap.get(key);
            List<JSONObject> jsonObjects = baseMapper.statCategoryBySubject(key, value);
            //分类
            jsonObjects.forEach(statCategorye->{
                String subjectCategory = statCategorye.getString("subjectCategory");
                Integer categoryNums = statCategorye.getInteger("categoryNums");
                params.put("sums",(categoryNums+params.getInteger("sums")));

                // 一级目录:　在职 退休 按照岗位统计
                List<JSONObject> statuses = baseMapper.statStatusBySubject(subjectCategory, value);
                statuses.forEach(status->{
                    String statusName = status.getString("status");
                    String statusNamePin = PinYinUtil.convertPY(statusName);

                    // 一级目录 统计岗位
                    List<JSONObject> jobCategoryes = baseMapper.statJobCategoryByList(subjectCategory, null,null,value, statusName);
                    jobCategoryes.forEach(jsonObject -> {
                        String jobCategory = jsonObject.getString("jobCategory");
                        String toPinyinString = PinYinUtil.convertPY(jobCategory);
                        Integer jobCategoryNums = jsonObject.getInteger("jobCategoryNums");
                        status.put(toPinyinString,jobCategoryNums);

                    });
                    statCategorye.put(statusNamePin,status);
                });


                List<JSONObject> subjectes  = new ArrayList<>();
                List<JSONObject> jsonList = baseMapper.statSubjectByList(subjectCategory, value);
                jsonList.forEach(subject->{
                    String subjectAttribution = subject.getString("subjectAttribution");

                    // 二级目录: 在职 退休
                    List<JSONObject> statusJSONes = baseMapper.statStatus(subjectCategory, subjectAttribution,null);
                    statusJSONes.forEach(status-> {
                        String statusName = status.getString("status");
                        String statusNamePin = PinYinUtil.convertPY(statusName);
                        Integer statusNums = status.getInteger("statusNums");
                        subject.put(statusNamePin,statusNums);
                    });

                    // 二级目录: 管理,教师,工勤,专业技术,其他 按照 岗位级别统计
                    List<JSONObject> jobCategoryes = baseMapper.statJobCategory(subjectCategory, subjectAttribution,null, null);
                    jobCategoryes.forEach(jobCategory->{
                        String jobCategoryName = jobCategory.getString("jobCategory");
                        String jobCategoryNamePinYin = PinYinUtil.convertPY(jobCategoryName);
                        //按岗位级别查询
                        List<JSONObject> jobLeveles = baseMapper.statJobLevel(subjectCategory, subjectAttribution, null,jobCategoryName);
                        jobLeveles.forEach(jobLevel->{
                            String jobLevelName = jobLevel.getString("jobLevel");

                            Integer jobLevelNums = jobLevel.getInteger("jobLevelNums");
                            if(CategoryUtil.highList.contains(jobLevelName)){
                                jobCategory.put(CategoryUtil.high,(jobLevelNums+(Integer) jobCategory.getOrDefault(CategoryUtil.high,0)));
                            }
                            if(CategoryUtil.middleList.contains(jobLevelName)){
                                jobCategory.put(CategoryUtil.middle,(jobLevelNums+(Integer)jobCategory.getOrDefault(CategoryUtil.middle,0)));
                            }
                            if(CategoryUtil.lowList.contains(jobLevelName)){
                                jobCategory.put(CategoryUtil.low,(jobLevelNums+(Integer)jobCategory.getOrDefault(CategoryUtil.low,0)));
                            }
                        });
                        // 岗位统计
                        subject.put(jobCategoryNamePinYin,jobCategory);

                    });

                    subjectes.add(subject);
                });

                statCategorye.put("subjectes",subjectes);

                categoryList.add(statCategorye);
            });
        });

        return categoryList;
    }

    private List<JSONObject> statCategoryData(List<String> ones,JSONObject params) {
        List<JSONObject> statCategoryes = baseMapper.statCategoryByList(ones);
        List<JSONObject> categoryList = new ArrayList<>();
        if(ones.isEmpty()) return categoryList;
        //分类
        statCategoryes.forEach(statCategorye->{
            String subjectCategory = statCategorye.getString("subjectCategory");
            Integer categoryNums = statCategorye.getInteger("categoryNums");
            params.put("sums",(categoryNums+params.getInteger("sums")));
            // 一级目录:　在职 退休 按照岗位统计
            List<JSONObject> statuses = baseMapper.statStatus(subjectCategory, null,null);
            statuses.forEach(status->{
                String statusName = status.getString("status");
                String statusNamePin = PinYinUtil.convertPY(statusName);

                // 一级目录 统计岗位
                List<JSONObject> jobCategoryes = baseMapper.statJobCategory(subjectCategory, null, null,statusName);
                jobCategoryes.forEach(jsonObject -> {
                    String jobCategory = jsonObject.getString("jobCategory");
                    String toPinyinString = PinYinUtil.convertPY(jobCategory);
                    Integer jobCategoryNums = jsonObject.getInteger("jobCategoryNums");
                    status.put(toPinyinString,jobCategoryNums);

                });
                statCategorye.put(statusNamePin,status);
            });


            List<JSONObject> jsonObjects = baseMapper.statSubject(subjectCategory, null);
            List<JSONObject> subjectes  = new ArrayList<>();
            jsonObjects.forEach(subject->{
                String subjectAttribution = subject.getString("subjectAttribution");

                // 二级目录: 在职 退休
                List<JSONObject> statusJSONes = baseMapper.statStatus(subjectCategory, subjectAttribution,null);
                statusJSONes.forEach(status-> {
                    String statusName = status.getString("status");
                    String statusNamePin = PinYinUtil.convertPY(statusName);
                    Integer statusNums = status.getInteger("statusNums");
                    subject.put(statusNamePin,statusNums);
                });

                // 二级目录: 管理,教师,工勤,专业技术,其他 按照 岗位级别统计
                List<JSONObject> jobCategoryes = baseMapper.statJobCategory(subjectCategory, subjectAttribution,null, null);
                jobCategoryes.forEach(jobCategory->{
                    String jobCategoryName = jobCategory.getString("jobCategory");
                    String jobCategoryNamePinYin = PinYinUtil.convertPY(jobCategoryName);
                    //按岗位级别查询
                    List<JSONObject> jobLeveles = baseMapper.statJobLevel(subjectCategory, subjectAttribution, null,jobCategoryName);
                    jobLeveles.forEach(jobLevel->{
                        String jobLevelName = jobLevel.getString("jobLevel");
                        Integer jobLevelNums = jobLevel.getInteger("jobLevelNums");
                        if(CategoryUtil.highList.contains(jobLevelName)){
                            jobCategory.put(CategoryUtil.high,(jobLevelNums+(Integer) jobCategory.getOrDefault(CategoryUtil.high,0)));
                        }
                        if(CategoryUtil.middleList.contains(jobLevelName)){
                            jobCategory.put(CategoryUtil.middle,(jobLevelNums+(Integer)jobCategory.getOrDefault(CategoryUtil.middle,0)));
                        }
                        if(CategoryUtil.lowList.contains(jobLevelName)){
                            jobCategory.put(CategoryUtil.low,(jobLevelNums+(Integer)jobCategory.getOrDefault(CategoryUtil.low,0)));
                        }
                    });
                    // 岗位统计
                    subject.put(jobCategoryNamePinYin,jobCategory);

                });

                subjectes.add(subject);
            });


            statCategorye.put("subjectes",subjectes);

            categoryList.add(statCategorye);
        });

        return categoryList;
    }

    @Override
    public List<JSONObject> statHome(String id, String category,Integer level) {
        // 统计分类数据
        List<JSONObject> statCategoryes = baseMapper.statCategory(category);
        List<JSONObject> list = new ArrayList<>();

        if(level == TeacherLevel.ONE.getLevel()){
            List<JSONObject> newStatCategoryes = new ArrayList<>();
            newStatCategoryes.addAll(statCategoryes);
            newStatCategoryes.forEach(statCategorye->{
                String subjectCategory = statCategorye.getString("subjectCategory");
                statCategoryes.add(CategoryEnum.getOrder(subjectCategory),statCategorye);
            });
        }


        //分类
        statCategoryes.forEach(statCategorye->{
            String subjectCategory = statCategorye.getString("subjectCategory");

            // 一级目录:　在职 退休 按照岗位统计
            List<JSONObject> statuses = baseMapper.statStatus(subjectCategory, null,null);
            statuses.forEach(status->{
                String statusName = status.getString("status");
                String statusNamePin = PinYinUtil.convertPY(statusName);

                // 一级目录 统计岗位
                List<JSONObject> jobCategoryes = baseMapper.statJobCategory(subjectCategory, null,null, statusName);
                jobCategoryes.forEach(jsonObject -> {
                    String jobCategory = jsonObject.getString("jobCategory");
                    String toPinyinString = PinYinUtil.convertPY(jobCategory);
                    Integer jobCategoryNums = jsonObject.getInteger("jobCategoryNums");
                    status.put(toPinyinString,jobCategoryNums);

                });
                statCategorye.put(statusNamePin,status);
            });


            List<JSONObject> jsonObjects = baseMapper.statSubject(subjectCategory, null);
            List<JSONObject> subjectes  = new ArrayList<>();
            jsonObjects.forEach(subject->{
                String subjectAttribution = subject.getString("subjectAttribution");

                // 二级目录: 在职 退休
                List<JSONObject> statusJSONes = baseMapper.statStatus(subjectCategory, subjectAttribution,null);
                statusJSONes.forEach(status-> {
                    String statusName = status.getString("status");
                    String statusNamePin = PinYinUtil.convertPY(statusName);
                    Integer statusNums = status.getInteger("statusNums");
                    subject.put(statusNamePin,statusNums);
                });

                // 二级目录: 管理,教师,工勤,专业技术,其他 按照 岗位级别统计
                List<JSONObject> jobCategoryes = baseMapper.statJobCategory(subjectCategory, subjectAttribution,null, null);
                jobCategoryes.forEach(jobCategory->{
                    String jobCategoryName = jobCategory.getString("jobCategory");
                    String jobCategoryNamePinYin = PinYinUtil.convertPY(jobCategoryName);
                    Integer jobCategoryNums = jobCategory.getInteger("jobCategoryNums");
                    //按岗位级别查询
                    List<JSONObject> jobLeveles = baseMapper.statJobLevel(subjectCategory, subjectAttribution,null, jobCategoryName);
                    jobLeveles.forEach(jobLevel->{
                        String jobLevelName = jobLevel.getString("jobLevel");
                        Integer jobLevelNums = jobLevel.getInteger("jobLevelNums");
                        jobCategory.put(jobLevelName,jobLevelNums);
                    });
                    // 岗位统计
                    subject.put(jobCategoryNamePinYin,jobCategory);

                });

                subjectes.add(subject);
            });


            statCategorye.put("subjectes",subjectes);

            list.add(statCategorye);
        });

        return list;
    }

    @Override
    public void findDetail(String id, Model model) {
        //查看人员的详细信息
        UTeacherInfo teacherInfo = this.selectOne(new EntityWrapper<UTeacherInfo>().eq("id", id));
        model.addAttribute("teacherInfo",teacherInfo);

        //工作学习经历
        List<UWorkExperience> uWorkExperiences = uWorkExperienceService.selectList(
                new EntityWrapper<UWorkExperience>()
                        .eq("teacher_id", id)
                        .orderBy("id",false));
        model.addAttribute("uWorkExperiences",uWorkExperiences);

        //学历学位变动
        List<UDegreeChanges> uDegreeChanges = uDegreeChangesService.selectList(new EntityWrapper<UDegreeChanges>().eq("teacher_id", id).orderBy("id", false));
        model.addAttribute("uDegreeChanges",uDegreeChanges);

        //职称变动
        List<UTitleChanges> uTitleChanges = uTitleChangesService.selectList(new EntityWrapper<UTitleChanges>()
                .eq("teacher_id", id).orderBy("id", false));
        model.addAttribute("uTitleChanges",uTitleChanges);

        //职务变动
        List<UPositionChanges> uPositionChanges = uPositionChangesService.selectList(new EntityWrapper<UPositionChanges>()
                .eq("teacher_id", id).orderBy("id", false));
        model.addAttribute("uPositionChanges",uPositionChanges);

        //教学业绩
        List<UTeachingPerformance> uTeachingPerformances = uTeachingPerformanceService.selectList(new EntityWrapper<UTeachingPerformance>()
                .eq("teacher_id", id).orderBy("id", false));

        model.addAttribute("uTeachingPerformances",uTeachingPerformances);


        //教学评价
        List<UTeachingEvaluation> uTeachingEvaluationes = uTeachingEvaluationService.selectList(new EntityWrapper<UTeachingEvaluation>()
                .eq("teacher_id", id).orderBy("id", false));
        model.addAttribute("uTeachingEvaluationes",uTeachingEvaluationes);


        //科研成果
        List<UResearchResults> uResearchResults = uResearchResultsService.selectList(new EntityWrapper<UResearchResults>()
                .eq("teacher_id", id).orderBy("id", false));
        model.addAttribute("uResearchResults",uResearchResults);

        //学习进修
        List<UStudyAndTraining> uStudyAndTrainings = uStudyAndTrainingService.selectList(new EntityWrapper<UStudyAndTraining>()
                .eq("teacher_id", id).orderBy("id", false));
        model.addAttribute("uStudyAndTrainings",uStudyAndTrainings);

        //社会兼职
        List<USocialPartTime> uSocialPartTimes = uSocialPartTimeService.selectList(new EntityWrapper<USocialPartTime>()
                .eq("teacher_id", id).orderBy("id", false));
        model.addAttribute("uSocialPartTimes",uSocialPartTimes);

        //荣誉获奖
        List<UHonorAward> uHonorAwards = uHonorAwardService.selectList(new EntityWrapper<UHonorAward>()
                .eq("teacher_id", id).orderBy("id", false));
        model.addAttribute("uHonorAwards",uHonorAwards);
    }

    @Override
    public List<String> findDistinctSubject(String subjectCategory) {
        return super.baseMapper.findDistinctSubject(subjectCategory);
    }

    @Override
    public List<String> findDistinctProfessional(String subjectCategory, String subjectAttribution) {
        return super.baseMapper.findDistinctProfessional(subjectCategory,subjectAttribution);
    }

}
